package me.luraframework.gateway.module.route;

import lombok.AllArgsConstructor;
import org.springframework.cloud.gateway.event.RefreshRoutesEvent;
import org.springframework.cloud.gateway.route.RouteDefinitionLocator;
import org.springframework.cloud.gateway.route.RouteDefinitionRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
import org.springframework.data.relational.core.query.Criteria;
import org.springframework.data.relational.core.query.Query;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.validation.Valid;

/**
 * @ description: GatewayController
 * @ author: Liu Ran
 * @ data: 7/10/23 20:12
 */

@RestController
@RequestMapping("gateway")
@AllArgsConstructor
public class GatewayController {

    private final GwApiRepository gwApiRepository;
    private final R2dbcEntityTemplate r2dbcEntityTemplate;
    private final ApplicationContext applicationContext;

    @GetMapping("routes")
    public Flux<GwApi> apis() {
        return gwApiRepository.findAll();
    }

    @PostMapping("routes")
    public Mono<GwApi> createApi(@Valid @RequestBody GwApi gwApi) {
        return r2dbcEntityTemplate.insert(gwApi)
                .doOnNext(g -> applicationContext.publishEvent(new RefreshRoutesEvent(this)));
    }

    @PutMapping("routes")
    public Mono<GwApi> updateApi(@RequestBody GwApi gwApi) {
        return r2dbcEntityTemplate.update(gwApi)
                .doOnNext(g -> applicationContext.publishEvent(new RefreshRoutesEvent(this)));
    }

    @DeleteMapping("routes/{name}")
    public Mono<Integer> updateApi(@PathVariable String name) {
        return r2dbcEntityTemplate.delete(Query.query(Criteria.where("name").is(name)), GwApi.class)
                .doOnNext(g -> applicationContext.publishEvent(new RefreshRoutesEvent(this)));
    }



}
